/* 
 * Modbus app for RTU.
 * Copyright (c) 2012  apleilx
 * All rights reserved.
 * no limite
 */

/* ----------------------- Platform includes --------------------------------*/
#define _MAPP_MODULE_
#include "mbapp.h"
#include "os_obj.h"                                          // RTOS object definitions
#include "pincfg.h"
#include "systask.h"

#define TEST_MODE       MB_RTU_SLAVE

mb_baud_tab_create;
    
uint8_t mbTestErrCnt = 0;
uint8_t mbTestOkCnt = 0;

typedef struct
{
    uint16_t pv_r[64];
    uint16_t pv_w[64];
    
    uint8_t line_w_req;
    uint8_t line_len;

	uint16_t sizobj;
} mb_tst_type;


mb_tst_type mb_tst;

volatile uint32_t dgs_err;
volatile uint32_t dgs_ok;

void dgus_callback(uint8_t CmdSite, uint8_t ErrSt)
{
    if(ErrSt)
    {
        dgs_err++;
    }
    else
    {
       dgs_ok++; 
        sys_st.i_air_temp = mb_tst.pv_r[4];
    }    
}

/*****************************************************************************//*!
* @brief   	Slave device handle.
*               
* @param   none
*
* @return  none
*
* @ Pass/ Fail criteria: none
*****************************************************************************/   
void modbus_task (void const *argument)
{
    mb_obj_init(&mb.obj01);
    mb_obj_init(&mb.obj02);
    
    mb01_Init(TEST_MODE, mb_baud_tab[MB_BAUD_9600], MB_PAR_NONE);
	mb.obj01.slave_id = 2;
	mb.obj01.timeout_set = 60;
    mb.obj01.os_event_send = mb_os_send;
    mb.obj01.os_rtu_end_event = 1;
    mb.obj01.os_timeout_event = 2;
    mb.obj01.rtu_rcv_end_delay_set = 5; 
    
    //mmb_stc_cmd_req(&mb.obj01,0,1,FUN_CODE_READ_REG,mb_tst.pv_r,0x1000,32,dgus_callback);
    
    //mmb_stc_cmd_req(&mb.obj01,3,1,FUN_CODE_READ_REG,mb_tst.reg_r,0x10,8,dgus_callback);
    //mmb_stc_cmd_req(&mb.obj01,7,1,FUN_CODE_READ_REG,&mb_tst.pv_w[16],0x22,16,dgus_callback);   
    //mmb_stc_cmd_req(&mb.obj01,1,1,FUN_CODE_WRITE_MULTIPLE_REG,mb_tst.pv_w,0x40,8,dgus_callback);
    //mmb_stc_cmd_req(&mb.obj01,4,1,FUN_CODE_W_R_MULTIPLE_REG,&mb_tst.pv_r[14],0x20,16,dgus_callback);
    //mmb_stc_cmd_req(&mb.obj01,5,1,FUN_CODE_W_R_MULTIPLE_REG,&mb_tst.pv_w[16],0x22,16,dgus_callback);
    //mmb_stc_cmd_req(&mb.obj01,6,1,FUN_CODE_WRITE_MULTIPLE_COIL,&mb_tst.pv_r[14],0x20,16,dgus_callback);

	mb_tst.sizobj = sizeof(mb.obj01);
	
    for(;;)
    {
        osSignalWait(0, ms_ticks(100));
        
        mb_poll(&mb.obj01);
    }
}


void mbTestCallBack(uint8_t CmdSite, uint8_t ErrSt){
    if(ErrSt)
        mbTestErrCnt++; 
    else
        mbTestOkCnt++;
}

